package com.mioto.ld.communication.mqtt.protocol;

import cn.hutool.core.util.StrUtil;
import com.google.gson.*;
import com.mioto.ld.communication.mqtt.protocol.model.DeviceMTypeEnum;
import com.mioto.ld.communication.mqtt.protocol.model.Message;
import com.mioto.ld.communication.mqtt.protocol.model.Payload;
import com.mioto.ld.communication.mqtt.protocol.model.device.DeviceDataReportPayload;

import java.lang.reflect.Type;
import java.util.*;

/**
 * @author mioto-qinxj
 * @date 2024/5/7
 * @desc
 */
public class PayloadDeserializer implements JsonDeserializer<Message> {
    @Override
    public Message deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jsonObj = jsonElement.getAsJsonObject();
        Message message = new Gson().fromJson(jsonElement,Message.class);
        if (jsonObj.has("messageBody")) {
            JsonElement content = jsonObj.getAsJsonObject("messageBody").get("payload");
            Payload payload;
            if (StrUtil.equals(DeviceMTypeEnum.getInstance(message.getMtype()).name(),DeviceMTypeEnum.DEVICE_DATA_REPORT.name())){
                Set<Map.Entry<String,JsonElement>> set = content.getAsJsonObject().entrySet();
                Map<String,Object> map = new HashMap<>(set.size());
                Iterator<Map.Entry<String,JsonElement>> iterable = set.iterator();
                Map.Entry<String,JsonElement> entry;
                while (iterable.hasNext()){
                    entry = iterable.next();
                    if (entry.getKey().equals("reportTime")){
                        map.put(entry.getKey(), new Date());
                    }else {
                        map.put(entry.getKey(), entry.getValue().getAsString());
                    }
                }
                payload = DeviceDataReportPayload.builder().attribute(map).build();
            }else {
                payload = new Gson().fromJson(content, DeviceMTypeEnum.getPayload(message.getMtype()));
            }
            message.getMessageBody().setPayload(payload);
        }
        return message;
    }
}
